from json import JSONDecodeError

from starlette.authentication import requires
from starlette.requests import Request

from injection_service.restful.common import get_password_hash
from injection_service.restful.common import Response
from injection_service.restful.common import verify_password
from injection_service.restful.common import create_access_token
from injection_service.restful.models import manually


class UserService:

    @classmethod
    async def create_user(cls, request: Request):
        """创建用户, json 数据传参"""
        try:
            form = await request.json()
            username = form.get("username")
            password = form.get("password")
            if all([username, password]):
                sql = 'insert into user (username, password) values ("%s", "%s")' % (username, get_password_hash(password))
                return Response(data=await manually(request, sql)).serialization
        except JSONDecodeError:
            return Response(errmsg="请求参数错误").serialization

    @classmethod
    async def user_list(cls, request: Request):
        """用户列表"""
        page = request.query_params.get("page", 1)
        limit = request.query_params.get("limit", 10)
        if all([page, limit]):
            sql = 'select id, username, created from user limit {skip},{page}'.format(skip=(page - 1) * limit,
                                                                                      page=limit)
            return Response(data=await manually(request, sql)).serialization
        return Response(errmsg="请求参数错误").serialization

    @classmethod
    async def user_token(cls, request: Request):
        """登录获取token， form数据"""
        form = await request.form()
        username = form.get("username")
        password = form.get("password")
        if all([username, password]):
            sql = f'select id, password from user where username = "{username}"'
            if data := await manually(request, sql):
                print(data)
                if verify_password(password, data[0]["password"]):
                    return Response(data={"token": create_access_token(str(data[0]["id"]))}).serialization
            return Response(errmsg="账号或密码错误").serialization
        return Response(errmsg="请求参数错误").serialization


class OrderService:

    @classmethod
    async def get_info(cls, request: Request):
        """根据用户名，订单价格过滤 所有账单"""
        username = request.query_params.get("username")
        price = request.query_params.get("price")
        sql = 'select order.id, order.name, order.count, order.price from user, `order` where ' \
              'user.id = order.user_id and user.username="' + username + '" and order.price = ' + price + ''
        # return Response(data=await manually(request, sql)).serialization